package com.modul.simpleLock.lockservice;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Collections;
import java.util.UUID;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/6 18:48
 * @Description: 可重入锁
 */
@Slf4j
public class ReentrantRedisLock implements RedisLock {

    // 获取枷锁的脚本
    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    // 获取释放锁的脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    private StringRedisTemplate redisTemplate;
    // 锁的key
    private String key;
    // 锁释放时间
    private String releaseTime;
    // 存入线程的前缀
    private final String ID_PREFIX = UUID.randomUUID().toString();

    // 静态代码加载锁
    static {
        // 加载获取锁的脚本
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("lock.lua")));
        log.info("打印获取锁的脚本：[{}]", JSONObject.toJSONString(LOCK_SCRIPT));
        // 加载释放锁的脚本
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("unlock.lua")));
        log.info("打印释放锁的脚本：[{}]", JSONObject.toJSONString(UNLOCK_SCRIPT));
    }

    // 构造函数
    public ReentrantRedisLock(StringRedisTemplate redisTemplate, String key) {
        this.redisTemplate = redisTemplate;
        this.key = key;
    }


    // 尝试获取锁
    @Override
    public Boolean tryLock(long releaseTime) {
        this.releaseTime = String.valueOf(releaseTime);
        // 执行脚本   Collections.singletonList(key) 当集合中只有一个元素的时候 使用这个方法 能够达到集合做优化分配
        Long result = redisTemplate.execute(LOCK_SCRIPT, Collections.singletonList(key), ID_PREFIX + Thread.currentThread().getId(), releaseTime);
        log.info("打印获取锁的的脚本相应的结果：[{}]", result);
        // 判断结果
        return result != null && result.intValue() == 1;
    }

    //释放锁
    @Override
    public void unlock() {
        //执行释放锁的脚本
        Long result = redisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(key), ID_PREFIX + Thread.currentThread().getId(), releaseTime);
        log.info("打印释放锁的的脚本相应的结果：[{}]", result);
    }

    @Override
    public Boolean getLock(String key) {
        return null;
    }
}
